﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WeChatApp.Helper;
using WeChatApp.Repositories;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Text;

namespace WeChatApp.Controllers
{
    public class BaseController:Controller
    {
        private RepositoryFactory _repositoryFactoryInst;
        public RepositoryFactory RepositoryFactoryInst
        {
            get
            {
                if (_repositoryFactoryInst == null)
                {
                    _repositoryFactoryInst = new RepositoryFactory(RepositoryConst.DefaultConnectString);
                }
                return _repositoryFactoryInst;
            }
        }
        public JsonResult JsonResultHelper(bool isSucceed, object msg)
        {
            return Json(new { IsSucceed = isSucceed, Message = msg });
        }
        public JsonResult JsonResultHelper(bool isSucceed, string msg)
        {
            return Json(new { IsSucceed = isSucceed, Message = msg });
        }
        public JsonResult JsonResultHelper<T>(List<T> dataList,int Count,string msg="查询成功")
        {
            return Json(new { code= Count > 0?0:1,msg= Count > 0&&msg!="" ? "":msg,count= Count, data=dataList});
        }
        public string UrlQueryHelper(string url,string postData,string Method,string ContentType= "application/json")
        {
            //定义request并设置request的路径
            WebRequest request = WebRequest.Create(url);
            request.Method = Method;
            //初始化request参数
            //设置参数的编码格式,解决中文乱码
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            //设置request的MINE类型及内容长度
            request.ContentType = ContentType;
            request.ContentLength = byteArray.Length;
            //打开request字符流
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            //定义response为前面的request相应
            WebResponse response = request.GetResponse();
            string code = ((HttpWebResponse)response).StatusDescription;
            //定义response字符流
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            return responseFromServer;
        }
    }
}
